<template>
  <div class="task-profitloss-container">
    <el-card shadow="never" class="header-card">
      <div class="page-header">
        <div class="header-content">
          <el-icon class="header-icon" :size="28"><Coin /></el-icon>
          <div class="header-text">
            <h2>任务单盈亏汇总</h2>
            <p>{{ taskInfo.taskNo }} - {{ taskInfo.taskName }}</p>
          </div>
        </div>
        <div class="header-actions">
          <el-button @click="handleBack">
            <el-icon><Back /></el-icon>
            返回任务列表
          </el-button>
          <el-button type="primary" @click="handleExport">
            <el-icon><Download /></el-icon>
            导出报表
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 任务基本信息 -->
    <el-card shadow="never" class="info-card">
      <el-descriptions :column="3" border>
        <el-descriptions-item label="任务单号">
          <el-tag type="primary" size="large">{{ taskInfo.taskNo }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="任务名称">{{ taskInfo.taskName }}</el-descriptions-item>
        <el-descriptions-item label="任务状态">
          <el-tag :type="getStatusType(taskInfo.status)" size="large">
            {{ getStatusName(taskInfo.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="盘点仓库">{{ taskInfo.warehouseName }}</el-descriptions-item>
        <el-descriptions-item label="负责人">{{ taskInfo.responsiblePerson }}</el-descriptions-item>
        <el-descriptions-item label="盘点进度">
          <el-progress :percentage="taskInfo.progress" :status="taskInfo.progress === 100 ? 'success' : ''" />
        </el-descriptions-item>
        <el-descriptions-item label="计划时间">
          {{ taskInfo.planStartDate }} 至 {{ taskInfo.planEndDate }}
        </el-descriptions-item>
        <el-descriptions-item label="实际时间">
          {{ taskInfo.actualStartDate || '-' }} 至 {{ taskInfo.actualEndDate || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ taskInfo.createTime }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 盈亏汇总大卡片 -->
    <div class="summary-section">
      <div class="summary-title">
        <el-icon><TrendCharts /></el-icon>
        <span>任务盈亏汇总</span>
        <el-tag size="small" style="margin-left: 12px;">汇总该任务下所有{{ taskInfo.sheetCount }}张盘点单的盈亏</el-tag>
      </div>
      
      <div class="summary-grid">
        <el-card shadow="hover" class="summary-card primary">
          <div class="card-icon">
            <el-icon :size="50"><Memo /></el-icon>
          </div>
          <div class="card-content">
            <div class="card-label">盘点单数量</div>
            <div class="card-value">{{ taskInfo.sheetCount }}</div>
            <div class="card-desc">已完成{{ completedSheets }}张</div>
          </div>
        </el-card>

        <el-card shadow="hover" class="summary-card success">
          <div class="card-icon">
            <el-icon :size="50"><CaretTop /></el-icon>
          </div>
          <div class="card-content">
            <div class="card-label">盘盈金额</div>
            <div class="card-value profit-value">+¥{{ Math.abs(taskInfo.profitAmount || 0).toLocaleString() }}</div>
            <div class="card-desc">{{ profitSheetCount }}张盘点单盘盈</div>
          </div>
        </el-card>

        <el-card shadow="hover" class="summary-card danger">
          <div class="card-icon">
            <el-icon :size="50"><CaretBottom /></el-icon>
          </div>
          <div class="card-content">
            <div class="card-label">盘亏金额</div>
            <div class="card-value loss-value">-¥{{ Math.abs(taskInfo.lossAmount || 0).toLocaleString() }}</div>
            <div class="card-desc">{{ lossSheetCount }}张盘点单盘亏</div>
          </div>
        </el-card>

        <el-card shadow="hover" class="summary-card highlight">
          <div class="card-icon">
            <el-icon :size="50"><DataAnalysis /></el-icon>
          </div>
          <div class="card-content">
            <div class="card-label">净盈亏金额</div>
            <div class="card-value" :class="getDiffClass(taskInfo.totalDiffAmount || 0)">
              {{ (taskInfo.totalDiffAmount || 0) > 0 ? '+' : '' }}¥{{ Math.abs(taskInfo.totalDiffAmount || 0).toLocaleString() }}
            </div>
            <div class="card-desc">盈亏率：{{ profitLossRate }}%</div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 盘点单明细列表 -->
    <el-card shadow="never">
      <div class="section-title">
        <el-icon><List /></el-icon>
        <span>盘点单明细（{{ sheets.length }}张）</span>
      </div>

      <el-table :data="sheets" stripe border>
        <el-table-column type="expand">
          <template #default="{ row }">
            <div style="padding: 20px;">
              <h4 style="margin-top: 0; margin-bottom: 12px;">
                <el-icon><Box /></el-icon>
                盘点商品明细（{{ row.items?.length || 0 }}个商品）
              </h4>
              <el-table :data="row.items" border size="small" v-if="row.items && row.items.length > 0">
                <el-table-column prop="productCode" label="商品编码" width="150" />
                <el-table-column prop="productName" label="商品名称" min-width="200" />
                <el-table-column prop="bookQty" label="账面数量" width="120" align="right" />
                <el-table-column prop="actualQty" label="实盘数量" width="120" align="right">
                  <template #default="{ row: item }">
                    <span :class="{ 'diff-highlight': item.bookQty !== item.actualQty }">
                      {{ item.actualQty }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="盈亏数量" width="120" align="right">
                  <template #default="{ row: item }">
                    <span :class="getDiffClass(item.diffQty)">
                      {{ item.diffQty > 0 ? '+' : '' }}{{ item.diffQty }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column prop="unitPrice" label="单价" width="120" align="right">
                  <template #default="{ row: item }">
                    ¥{{ item.unitPrice.toFixed(2) }}
                  </template>
                </el-table-column>
                <el-table-column label="盈亏金额" width="150" align="right">
                  <template #default="{ row: item }">
                    <span :class="getDiffClass(item.diffAmount)">
                      {{ item.diffAmount > 0 ? '+' : '' }}¥{{ Math.abs(item.diffAmount).toFixed(2) }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column prop="remark" label="备注" min-width="150" />
              </el-table>
              <el-empty v-else description="该盘点单暂无明细数据" :image-size="60" />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="sheetNo" label="盘点单号" width="180" fixed>
          <template #default="{ row }">
            <el-link type="primary" @click="handleViewSheet(row)">{{ row.sheetNo }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="warehouseName" label="仓库" width="120" />
        <el-table-column prop="checkPerson" label="盘点人" width="100" />
        <el-table-column prop="checkTime" label="盘点时间" width="180" />
        <el-table-column prop="totalItems" label="商品数" width="100" align="right" />
        <el-table-column label="盘点单盈亏" width="180" align="right">
          <template #default="{ row }">
            <span :class="getDiffClass(row.totalDiffAmount)" class="sheet-diff">
              {{ row.totalDiffAmount > 0 ? '+' : '' }}¥{{ Math.abs(row.totalDiffAmount).toFixed(2) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getSheetStatusType(row.status)" size="small">
              {{ getSheetStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="占比" width="120" align="right">
          <template #default="{ row }">
            <el-progress 
              :percentage="calculatePercentage(row.totalDiffAmount)" 
              :stroke-width="6"
              :show-text="false"
            />
            <span style="margin-left: 8px; font-size: 13px;">
              {{ calculatePercentage(row.totalDiffAmount) }}%
            </span>
          </template>
        </el-table-column>
      </el-table>

      <div class="table-footer">
        <div class="footer-summary">
          <span class="summary-label">盘点单汇总：</span>
          <span class="summary-item">
            共{{ sheets.length }}张盘点单，
          </span>
          <span class="summary-item">
            盘盈{{ profitSheetCount }}张（+¥{{ Math.abs(taskInfo.profitAmount || 0).toLocaleString() }}），
          </span>
          <span class="summary-item">
            盘亏{{ lossSheetCount }}张（-¥{{ Math.abs(taskInfo.lossAmount || 0).toLocaleString() }}），
          </span>
          <span class="summary-item">
            净盈亏：<span :class="getDiffClass(taskInfo.totalDiffAmount || 0)" class="net-amount">
              {{ (taskInfo.totalDiffAmount || 0) > 0 ? '+' : '' }}¥{{ Math.abs(taskInfo.totalDiffAmount || 0).toLocaleString() }}
            </span>
          </span>
        </div>
      </div>
    </el-card>

    <!-- 盈亏分析 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="12">
        <el-card shadow="never">
          <div class="section-title">
            <el-icon><PieChart /></el-icon>
            <span>盘点单盈亏分布</span>
          </div>
          <div class="chart-placeholder">
            <el-icon :size="60" color="#dcdfe6"><PieChart /></el-icon>
            <p>饼图：盘盈/盘亏/平衡盘点单占比</p>
            <div style="margin-top: 16px;">
              <el-tag type="success">盘盈：{{ profitSheetCount }}张</el-tag>
              <el-tag type="danger" style="margin: 0 8px;">盘亏：{{ lossSheetCount }}张</el-tag>
              <el-tag>平衡：{{ balanceSheetCount }}张</el-tag>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card shadow="never">
          <div class="section-title">
            <el-icon><TrendCharts /></el-icon>
            <span>盈亏趋势分析</span>
          </div>
          <div class="chart-placeholder">
            <el-icon :size="60" color="#dcdfe6"><TrendCharts /></el-icon>
            <p>柱状图：各盘点单盈亏对比</p>
            <el-tag type="info">图表组件待集成</el-tag>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 盈亏TOP榜 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="12">
        <el-card shadow="never">
          <div class="section-title">
            <el-icon><Top /></el-icon>
            <span>盘盈TOP商品</span>
          </div>
          <el-table :data="topProfitItems" stripe max-height="300">
            <el-table-column type="index" label="排名" width="70" />
            <el-table-column prop="productName" label="商品名称" min-width="150" />
            <el-table-column prop="sheetNo" label="来源盘点单" width="150" />
            <el-table-column prop="diffQty" label="盘盈数量" width="100" align="right">
              <template #default="{ row }">
                <span class="profit-text">+{{ row.diffQty }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="diffAmount" label="盘盈金额" width="120" align="right">
              <template #default="{ row }">
                <span class="profit-text">+¥{{ row.diffAmount.toFixed(2) }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card shadow="never">
          <div class="section-title">
            <el-icon><Bottom /></el-icon>
            <span>盘亏TOP商品</span>
          </div>
          <el-table :data="topLossItems" stripe max-height="300">
            <el-table-column type="index" label="排名" width="70" />
            <el-table-column prop="productName" label="商品名称" min-width="150" />
            <el-table-column prop="sheetNo" label="来源盘点单" width="150" />
            <el-table-column prop="diffQty" label="盘亏数量" width="100" align="right">
              <template #default="{ row }">
                <span class="loss-text">{{ row.diffQty }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="diffAmount" label="盘亏金额" width="120" align="right">
              <template #default="{ row }">
                <span class="loss-text">¥{{ Math.abs(row.diffAmount).toFixed(2) }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Coin, Back, Download, TrendCharts, Memo, CaretTop, CaretBottom,
  DataAnalysis, List, Box, PieChart, Top, Bottom
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

// 任务信息
const taskInfo = ref({
  id: route.query.taskId || 1,
  taskNo: 'CHK202401150001',
  taskName: '2024年1月全盘任务',
  type: 'full',
  warehouseId: 1,
  warehouseName: '主仓库',
  status: 'inProgress',
  planStartDate: '2024-01-15 08:00',
  planEndDate: '2024-01-17 18:00',
  actualStartDate: '2024-01-15 08:30',
  actualEndDate: null,
  responsiblePerson: '张三',
  progress: 65,
  createTime: '2024-01-14 10:00:00',
  // 汇总数据
  sheetCount: 5,
  totalDiffAmount: -69498,
  totalDiffQty: -12,
  profitAmount: 9495,
  lossAmount: -78993
})

// 盘点单列表
const sheets = ref([
  {
    id: 1,
    sheetNo: 'CHS202401150001',
    warehouseName: '主仓库',
    checkPerson: '张三',
    checkTime: '2024-01-15 10:00:00',
    totalItems: 8,
    totalDiffAmount: -15000,
    status: 'completed',
    items: [
      {
        productCode: 'P001',
        productName: 'iPhone 15 Pro Max',
        bookQty: 100,
        actualQty: 95,
        diffQty: -5,
        unitPrice: 9999,
        diffAmount: -49995,
        remark: '破损丢失'
      },
      {
        productCode: 'P002',
        productName: 'MacBook Pro',
        bookQty: 50,
        actualQty: 48,
        diffQty: -2,
        unitPrice: 14999,
        diffAmount: -29998,
        remark: '账实不符'
      },
      {
        productCode: 'P003',
        productName: 'AirPods Pro 2',
        bookQty: 200,
        actualQty: 205,
        diffQty: 5,
        unitPrice: 1899,
        diffAmount: 9495,
        remark: '未入库商品'
      }
    ]
  },
  {
    id: 2,
    sheetNo: 'CHS202401150002',
    warehouseName: '主仓库',
    checkPerson: '李四',
    checkTime: '2024-01-15 12:30:00',
    totalItems: 12,
    totalDiffAmount: -20500,
    status: 'completed',
    items: []
  },
  {
    id: 3,
    sheetNo: 'CHS202401150003',
    warehouseName: '主仓库',
    checkPerson: '王五',
    checkTime: '2024-01-15 14:00:00',
    totalItems: 6,
    totalDiffAmount: 9495,
    status: 'approved',
    items: []
  },
  {
    id: 4,
    sheetNo: 'CHS202401150004',
    warehouseName: '主仓库',
    checkPerson: '张三',
    checkTime: '2024-01-15 16:00:00',
    totalItems: 10,
    totalDiffAmount: -25493,
    status: 'completed',
    items: []
  },
  {
    id: 5,
    sheetNo: 'CHS202401150005',
    warehouseName: '主仓库',
    checkPerson: '李四',
    checkTime: null,
    totalItems: 0,
    totalDiffAmount: 0,
    status: 'pending',
    items: []
  }
])

// 盈亏TOP数据
const topProfitItems = ref([
  {
    productName: 'AirPods Pro 2',
    sheetNo: 'CHS202401150001',
    diffQty: 5,
    diffAmount: 9495
  },
  {
    productName: 'Apple Watch S9',
    sheetNo: 'CHS202401150003',
    diffQty: 3,
    diffAmount: 9597
  }
])

const topLossItems = ref([
  {
    productName: 'iPhone 15 Pro Max',
    sheetNo: 'CHS202401150001',
    diffQty: -5,
    diffAmount: -49995
  },
  {
    productName: 'iPad Pro 12.9',
    sheetNo: 'CHS202401150004',
    diffQty: -10,
    diffAmount: -47990
  },
  {
    productName: 'MacBook Pro',
    sheetNo: 'CHS202401150001',
    diffQty: -2,
    diffAmount: -29998
  }
])

// 计算属性
const completedSheets = computed(() => {
  return sheets.value.filter(s => s.status === 'completed' || s.status === 'approved').length
})

const profitSheetCount = computed(() => {
  return sheets.value.filter(s => s.totalDiffAmount > 0).length
})

const lossSheetCount = computed(() => {
  return sheets.value.filter(s => s.totalDiffAmount < 0).length
})

const balanceSheetCount = computed(() => {
  return sheets.value.filter(s => s.totalDiffAmount === 0).length
})

const profitLossRate = computed(() => {
  // 简化计算：盈亏率 = 净盈亏金额 / 总库存金额 * 100
  // 这里假设总库存金额
  const totalInventoryValue = 5000000 // 假设总库存500万
  const rate = ((taskInfo.value.totalDiffAmount || 0) / totalInventoryValue) * 100
  return rate.toFixed(2)
})

const calculatePercentage = (amount) => {
  const total = Math.abs(taskInfo.value.profitAmount || 0) + Math.abs(taskInfo.value.lossAmount || 0)
  if (total === 0) return 0
  return Math.round((Math.abs(amount) / total) * 100)
}

// 方法
const handleBack = () => {
  router.push('/inventory/check-tasks')
}

const handleViewSheet = (sheet) => {
  router.push(`/inventory/check-detail?id=${sheet.id}`)
}

const handleExport = () => {
  ElMessage.success('导出任务盈亏报表')
}

const getStatusName = (status) => {
  const map = {
    pending: '待盘点',
    inProgress: '盘点中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return map[status] || status
}

const getStatusType = (status) => {
  const map = {
    pending: 'warning',
    inProgress: '',
    completed: 'success',
    cancelled: 'info'
  }
  return map[status] || ''
}

const getSheetStatusName = (status) => {
  const map = {
    pending: '待盘',
    checking: '盘点中',
    completed: '已完成',
    approved: '已审核'
  }
  return map[status] || status
}

const getSheetStatusType = (status) => {
  const map = {
    pending: 'info',
    checking: 'warning',
    completed: '',
    approved: 'success'
  }
  return map[status] || ''
}

const getDiffClass = (value) => {
  if (value > 0) return 'profit-text'
  if (value < 0) return 'loss-text'
  return ''
}
</script>

<style scoped>
.task-profitloss-container {
  padding: 20px;
}

.header-card,
.info-card {
  margin-bottom: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon {
  color: #409EFF;
}

.header-text h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.header-text p {
  margin: 4px 0 0 0;
  font-size: 14px;
  color: #909399;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.summary-section {
  margin-bottom: 20px;
}

.summary-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 20px;
  padding: 16px 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7ed 100%);
  border-radius: 8px;
}

.summary-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}

.summary-card {
  border-left: 4px solid;
  transition: all 0.3s;
}

.summary-card:hover {
  transform: translateY(-6px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
}

.summary-card.primary {
  border-left-color: #409EFF;
}

.summary-card.success {
  border-left-color: #67C23A;
}

.summary-card.danger {
  border-left-color: #F56C6C;
}

.summary-card.highlight {
  border-left-color: #E6A23C;
  background: linear-gradient(135deg, #fffbf0 0%, #fff7e6 100%);
}

.card-icon {
  text-align: center;
  margin-bottom: 16px;
  color: #409EFF;
  opacity: 0.3;
}

.card-content {
  text-align: center;
}

.card-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 12px;
}

.card-value {
  font-size: 36px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
  line-height: 1;
}

.card-value.profit-value {
  color: #67C23A;
}

.card-value.loss-value {
  color: #F56C6C;
}

.card-desc {
  font-size: 13px;
  color: #606266;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 2px solid #e4e7ed;
}

.sheet-diff {
  font-weight: 600;
  font-size: 15px;
}

.profit-text {
  color: #67C23A;
  font-weight: 500;
}

.loss-text {
  color: #F56C6C;
  font-weight: 500;
}

.diff-highlight {
  color: #E6A23C;
  font-weight: 500;
}

.table-footer {
  margin-top: 20px;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 8px;
}

.footer-summary {
  font-size: 15px;
  color: #606266;
  line-height: 1.8;
}

.summary-label {
  font-weight: 600;
  color: #303133;
  margin-right: 8px;
}

.summary-item {
  margin-right: 16px;
}

.net-amount {
  font-size: 18px;
  font-weight: 700;
}

.chart-placeholder {
  height: 280px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #fafafa;
  border-radius: 8px;
}

.chart-placeholder p {
  margin: 16px 0;
  color: #606266;
  font-size: 14px;
}
</style>

